<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Databases &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../index.html" />
    <link rel="up" title="API Reference" href="index.html" />
    <link rel="next" title="django-admin.py and manage.py" href="django-admin.html" />
    <link rel="prev" title="django.contrib.webdesign" href="contrib/webdesign.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="contrib/webdesign.html" title="django.contrib.webdesign">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="django-admin.html" title="django-admin.py and manage.py">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-databases">
            
  <div class="section" id="s-databases">
<span id="databases"></span><h1>Databases<a class="headerlink" href="#databases" title="Permalink to this headline">¶</a></h1>
<p>Django attempts to support as many features as possible on all database
backends. However, not all database backends are alike, and we&#8217;ve had to make
design decisions on which features to support and which assumptions we can make
safely.</p>
<p>This file describes some of the features that might be relevant to Django
usage. Of course, it is not intended as a replacement for server-specific
documentation or reference manuals.</p>
<div class="section" id="s-general-notes">
<span id="general-notes"></span><h2>General notes<a class="headerlink" href="#general-notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-persistent-connections">
<span id="s-persistent-database-connections"></span><span id="persistent-connections"></span><span id="persistent-database-connections"></span><h3>Persistent connections<a class="headerlink" href="#persistent-connections" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Persistent connections avoid the overhead of re-establishing a connection to
the database in each request. They&#8217;re controlled by the
<a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">CONN_MAX_AGE</span></tt></a> parameter which defines the maximum lifetime of a
connection. It can be set independently for each database.</p>
<p>The default value is <tt class="docutils literal"><span class="pre">0</span></tt>, preserving the historical behavior of closing the
database connection at the end of each request. To enable persistent
connections, set <a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">CONN_MAX_AGE</span></tt></a> to a positive number of seconds. For
unlimited persistent connections, set it to <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
<div class="section" id="s-connection-management">
<span id="connection-management"></span><h4>Connection management<a class="headerlink" href="#connection-management" title="Permalink to this headline">¶</a></h4>
<p>Django opens a connection to the database when it first makes a database
query. It keeps this connection open and reuses it in subsequent requests.
Django closes the connection once it exceeds the maximum age defined by
<a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">CONN_MAX_AGE</span></tt></a> or when it isn&#8217;t usable any longer.</p>
<p>In detail, Django automatically opens a connection to the database whenever it
needs one and doesn&#8217;t have one already — either because this is the first
connection, or because the previous connection was closed.</p>
<p>At the beginning of each request, Django closes the connection if it has
reached its maximum age. If your database terminates idle connections after
some time, you should set <a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">CONN_MAX_AGE</span></tt></a> to a lower value, so that
Django doesn&#8217;t attempt to use a connection that has been terminated by the
database server. (This problem may only affect very low traffic sites.)</p>
<p>At the end of each request, Django closes the connection if it has reached its
maximum age or if it is in an unrecoverable error state. If any database
errors have occurred while processing the requests, Django checks whether the
connection still works, and closes it if it doesn&#8217;t. Thus, database errors
affect at most one request; if the connection becomes unusable, the next
request gets a fresh connection.</p>
</div>
<div class="section" id="s-caveats">
<span id="caveats"></span><h4>Caveats<a class="headerlink" href="#caveats" title="Permalink to this headline">¶</a></h4>
<p>Since each thread maintains its own connection, your database must support at
least as many simultaneous connections as you have worker threads.</p>
<p>Sometimes a database won&#8217;t be accessed by the majority of your views, for
example because it&#8217;s the database of an external system, or thanks to caching.
In such cases, you should set <a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><tt class="xref std std-setting docutils literal"><span class="pre">CONN_MAX_AGE</span></tt></a> to a low value or even
<tt class="docutils literal"><span class="pre">0</span></tt>, because it doesn&#8217;t make sense to maintain a connection that&#8217;s unlikely
to be reused. This will help keep the number of simultaneous connections to
this database small.</p>
<p>The development server creates a new thread for each request it handles,
negating the effect of persistent connections. Don&#8217;t enable them during
development.</p>
<p>When Django establishes a connection to the database, it sets up appropriate
parameters, depending on the backend being used. If you enable persistent
connections, this setup is no longer repeated every request. If you modify
parameters such as the connection&#8217;s isolation level or time zone, you should
either restore Django&#8217;s defaults at the end of each request, force an
appropriate value at the beginning of each request, or disable persistent
connections.</p>
</div>
</div>
<div class="section" id="s-encoding">
<span id="encoding"></span><h3>Encoding<a class="headerlink" href="#encoding" title="Permalink to this headline">¶</a></h3>
<p>Django assumes that all databases use UTF-8 encoding. Using other encodings may
result in unexpected behavior such as &#8220;value too long&#8221; errors from your
database for data that is valid in Django. See the database specific notes
below for information on how to set up your database correctly.</p>
</div>
</div>
<div class="section" id="s-postgresql-notes">
<span id="s-id1"></span><span id="postgresql-notes"></span><span id="id1"></span><h2>PostgreSQL notes<a class="headerlink" href="#postgresql-notes" title="Permalink to this headline">¶</a></h2>
<p>Django supports PostgreSQL 8.4 and higher.</p>
<p>If you&#8217;re on Windows, check out the unofficial <a class="reference external" href="http://stickpeople.com/projects/python/win-psycopg/">compiled Windows version</a>
of psycopg2.</p>
<div class="section" id="s-postgresql-connection-settings">
<span id="postgresql-connection-settings"></span><h3>PostgreSQL connection settings<a class="headerlink" href="#postgresql-connection-settings" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference internal" href="settings.html#std:setting-HOST"><tt class="xref std std-setting docutils literal"><span class="pre">HOST</span></tt></a> for details.</p>
</div>
<div class="section" id="s-optimizing-postgresql-s-configuration">
<span id="optimizing-postgresql-s-configuration"></span><h3>Optimizing PostgreSQL&#8217;s configuration<a class="headerlink" href="#optimizing-postgresql-s-configuration" title="Permalink to this headline">¶</a></h3>
<p>Django needs the following parameters for its database connections:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">client_encoding</span></tt>: <tt class="docutils literal"><span class="pre">'UTF8'</span></tt>,</li>
<li><tt class="docutils literal"><span class="pre">default_transaction_isolation</span></tt>: <tt class="docutils literal"><span class="pre">'read</span> <span class="pre">committed'</span></tt> by default,
or the value set in the connection options (see below),</li>
<li><tt class="docutils literal"><span class="pre">timezone</span></tt>: <tt class="docutils literal"><span class="pre">'UTC'</span></tt> when <a class="reference internal" href="settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, value of
<a class="reference internal" href="settings.html#std:setting-TIME_ZONE"><tt class="xref std std-setting docutils literal"><span class="pre">TIME_ZONE</span></tt></a> otherwise.</li>
</ul>
<p>If these parameters already have the correct values, Django won&#8217;t set them for
every new connection, which improves performance slightly. You can configure
them directly in <tt class="file docutils literal"><span class="pre">postgresql.conf</span></tt> or more conveniently per database
user with <a class="reference external" href="http://www.postgresql.org/docs/current/interactive/sql-alterrole.html">ALTER ROLE</a>.</p>
<p>Django will work just fine without this optimization, but each new connection
will do some additional queries to set these parameters.</p>
</div>
<div class="section" id="s-autocommit-mode">
<span id="s-postgresql-autocommit-mode"></span><span id="autocommit-mode"></span><span id="postgresql-autocommit-mode"></span><h3>Autocommit mode<a class="headerlink" href="#autocommit-mode" title="Permalink to this headline">¶</a></h3>
<div class="versionchanged">
<span class="title">Changed in Django 1.6.</span> </div>
<p>In previous versions of Django, database-level autocommit could be enabled by
setting the <tt class="docutils literal"><span class="pre">autocommit</span></tt> key in the <a class="reference internal" href="settings.html#std:setting-OPTIONS"><tt class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></tt></a> part of your database
configuration in <a class="reference internal" href="settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="c"># ...</span>
    <span class="s">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;autocommit&#39;</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Since Django 1.6, autocommit is turned on by default. This configuration is
ignored and can be safely removed.</p>
</div>
<div class="section" id="s-isolation-level">
<span id="s-database-isolation-level"></span><span id="isolation-level"></span><span id="database-isolation-level"></span><h3>Isolation level<a class="headerlink" href="#isolation-level" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Like PostgreSQL itself, Django defaults to the <tt class="docutils literal"><span class="pre">READ</span> <span class="pre">COMMITTED</span></tt> <a class="reference external" href="http://www.postgresql.org/docs/current/static/transaction-iso.html">isolation
level</a>. If you need a higher isolation level such as <tt class="docutils literal"><span class="pre">REPEATABLE</span> <span class="pre">READ</span></tt> or
<tt class="docutils literal"><span class="pre">SERIALIZABLE</span></tt>, set it in the <a class="reference internal" href="settings.html#std:setting-OPTIONS"><tt class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></tt></a> part of your database
configuration in <a class="reference internal" href="settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">psycopg2.extensions</span>

<span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="c"># ...</span>
    <span class="s">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;isolation_level&#39;</span><span class="p">:</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">ISOLATION_LEVEL_SERIALIZABLE</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Under higher isolation levels, your application should be prepared to
handle exceptions raised on serialization failures. This option is
designed for advanced uses.</p>
</div>
</div>
<div class="section" id="s-indexes-for-varchar-and-text-columns">
<span id="indexes-for-varchar-and-text-columns"></span><h3>Indexes for <tt class="docutils literal"><span class="pre">varchar</span></tt> and <tt class="docutils literal"><span class="pre">text</span></tt> columns<a class="headerlink" href="#indexes-for-varchar-and-text-columns" title="Permalink to this headline">¶</a></h3>
<p>When specifying <tt class="docutils literal"><span class="pre">db_index=True</span></tt> on your model fields, Django typically
outputs a single <tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">INDEX</span></tt> statement.  However, if the database type
for the field is either <tt class="docutils literal"><span class="pre">varchar</span></tt> or <tt class="docutils literal"><span class="pre">text</span></tt> (e.g., used by <tt class="docutils literal"><span class="pre">CharField</span></tt>,
<tt class="docutils literal"><span class="pre">FileField</span></tt>, and <tt class="docutils literal"><span class="pre">TextField</span></tt>), then Django will create
an additional index that uses an appropriate <a class="reference external" href="http://www.postgresql.org/docs/current/static/indexes-opclass.html">PostgreSQL operator class</a>
for the column.  The extra index is necessary to correctly perform
lookups that use the <tt class="docutils literal"><span class="pre">LIKE</span></tt> operator in their SQL, as is done with the
<tt class="docutils literal"><span class="pre">contains</span></tt> and <tt class="docutils literal"><span class="pre">startswith</span></tt> lookup types.</p>
</div>
</div>
<div class="section" id="s-mysql-notes">
<span id="s-id3"></span><span id="mysql-notes"></span><span id="id3"></span><h2>MySQL notes<a class="headerlink" href="#mysql-notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-version-support">
<span id="version-support"></span><h3>Version support<a class="headerlink" href="#version-support" title="Permalink to this headline">¶</a></h3>
<p>Django supports MySQL 5.0.3 and higher.</p>
<p>Django&#8217;s <tt class="docutils literal"><span class="pre">inspectdb</span></tt> feature uses the <tt class="docutils literal"><span class="pre">information_schema</span></tt> database, which
contains detailed data on all database schemas.</p>
<p>Django expects the database to support Unicode (UTF-8 encoding) and delegates to
it the task of enforcing transactions and referential integrity. It is important
to be aware of the fact that the two latter ones aren&#8217;t actually enforced by
MySQL when using the MyISAM storage engine, see the next section.</p>
</div>
<div class="section" id="s-storage-engines">
<span id="s-mysql-storage-engines"></span><span id="storage-engines"></span><span id="mysql-storage-engines"></span><h3>Storage engines<a class="headerlink" href="#storage-engines" title="Permalink to this headline">¶</a></h3>
<p>MySQL has several <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/storage-engines.html">storage engines</a>. You can change the default storage engine
in the server configuration.</p>
<p>Until MySQL 5.5.4, the default engine was <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/myisam-storage-engine.html">MyISAM</a> <a class="footnote-reference" href="#id6" id="id4">[1]</a>. The main drawbacks of
MyISAM are that it doesn&#8217;t support transactions or enforce foreign-key
constraints. On the plus side, it was the only engine that supported full-text
indexing and searching until MySQL 5.6.4.</p>
<p>Since MySQL 5.5.5, the default storage engine is <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/innodb-storage-engine.html">InnoDB</a>. This engine is fully
transactional and supports foreign key references. It&#8217;s probably the best
choice at this point. However, note that the InnoDB autoincrement counter
is lost on a MySQL restart because it does not remember the
<tt class="docutils literal"><span class="pre">AUTO_INCREMENT</span></tt> value, instead recreating it as &#8220;max(id)+1&#8221;. This may
result in an inadvertent reuse of <a class="reference internal" href="models/fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a> values.</p>
<p>If you upgrade an existing project to MySQL 5.5.5 and subsequently add some
tables, ensure that your tables are using the same storage engine (i.e. MyISAM
vs. InnoDB). Specifically, if tables that have a <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> between them
use different storage engines, you may see an error like the following when
running <tt class="docutils literal"><span class="pre">migrate</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre>_mysql_exceptions.OperationalError: (
    1005, &quot;Can&#39;t create table &#39;\\db_name\\.#sql-4a8_ab&#39; (errno: 150)&quot;
)
</pre></div>
</div>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[1]</a></td><td>Unless this was changed by the packager of your MySQL package. We&#8217;ve
had reports that the Windows Community Server installer sets up InnoDB as
the default storage engine, for example.</td></tr>
</tbody>
</table>
</div>
<div class="section" id="s-mysql-db-api-drivers">
<span id="s-id7"></span><span id="mysql-db-api-drivers"></span><span id="id7"></span><h3>MySQL DB API Drivers<a class="headerlink" href="#mysql-db-api-drivers" title="Permalink to this headline">¶</a></h3>
<p>The Python Database API is described in <a class="reference external" href="http://www.python.org/dev/peps/pep-0249/">PEP 249</a>. MySQL has three prominent
drivers that implement this API:</p>
<ul class="simple">
<li><a class="reference external" href="https://pypi.python.org/pypi/MySQL-python/1.2.4">MySQLdb</a> is a native driver that has been developed and supported for over
a decade by Andy Dustman.</li>
<li><a class="reference external" href="https://pypi.python.org/pypi/mysqlclient">mysqlclient</a> is a fork of <tt class="docutils literal"><span class="pre">MySQLdb</span></tt> which notably supports Python 3 and
can be used as a drop-in replacement for MySQLdb. At the time of this writing,
this is <strong>the recommended choice</strong> for using MySQL with Django.</li>
<li><a class="reference external" href="http://dev.mysql.com/downloads/connector/python">MySQL Connector/Python</a> is a pure Python driver from Oracle that does not
require the MySQL client library or any Python modules outside the standard
library.</li>
</ul>
<p>All these drivers are thread-safe and provide connection pooling. <tt class="docutils literal"><span class="pre">MySQLdb</span></tt>
is the only one not supporting Python 3 currently.</p>
<p>In addition to a DB API driver, Django needs an adapter to access the database
drivers from its ORM. Django provides an adapter for MySQLdb/mysqlclient while
MySQL Connector/Python includes <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/connector-python-django-backend.html">its own</a>.</p>
<div class="section" id="s-id8">
<span id="id8"></span><h4>MySQLdb<a class="headerlink" href="#id8" title="Permalink to this headline">¶</a></h4>
<p>Django requires MySQLdb version 1.2.1p2 or later.</p>
<p>At the time of writing, the latest release of MySQLdb (1.2.5) doesn&#8217;t support
Python 3. In order to use MySQLdb under Python 3, you&#8217;ll have to install
<tt class="docutils literal"><span class="pre">mysqlclient</span></tt> instead.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>There are known issues with the way MySQLdb converts date strings into
datetime objects. Specifically, date strings with value <tt class="docutils literal"><span class="pre">0000-00-00</span></tt> are
valid for MySQL but will be converted into <tt class="docutils literal"><span class="pre">None</span></tt> by MySQLdb.</p>
<p class="last">This means you should be careful while using <a class="reference internal" href="django-admin.html#django-admin-loaddata"><tt class="xref std std-djadmin docutils literal"><span class="pre">loaddata</span></tt></a> and
<a class="reference internal" href="django-admin.html#django-admin-dumpdata"><tt class="xref std std-djadmin docutils literal"><span class="pre">dumpdata</span></tt></a> with rows that may have <tt class="docutils literal"><span class="pre">0000-00-00</span></tt> values, as they
will be converted to <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
</div>
</div>
<div class="section" id="s-id9">
<span id="id9"></span><h4>mysqlclient<a class="headerlink" href="#id9" title="Permalink to this headline">¶</a></h4>
<p>Django requires <a class="reference external" href="https://pypi.python.org/pypi/mysqlclient">mysqlclient</a> 1.3.3 or later. Note that Python 3.2 is not
supported. Except for the Python 3.3+ support, mysqlclient should mostly behave
the same as MySQLDB.</p>
</div>
<div class="section" id="s-id10">
<span id="id10"></span><h4>MySQL Connector/Python<a class="headerlink" href="#id10" title="Permalink to this headline">¶</a></h4>
<p>MySQL Connector/Python is available from the <a class="reference external" href="http://dev.mysql.com/downloads/connector/python/">download page</a>.
The Django adapter is available in versions 1.1.X and later. It may not
support the most recent releases of Django.</p>
</div>
</div>
<div class="section" id="s-time-zone-definitions">
<span id="s-mysql-time-zone-definitions"></span><span id="time-zone-definitions"></span><span id="mysql-time-zone-definitions"></span><h3>Time zone definitions<a class="headerlink" href="#time-zone-definitions" title="Permalink to this headline">¶</a></h3>
<p>If you plan on using Django&#8217;s <a class="reference internal" href="../topics/i18n/timezones.html"><em>timezone support</em></a>,
use <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/mysql-tzinfo-to-sql.html">mysql_tzinfo_to_sql</a> to load time zone tables into the MySQL database.
This needs to be done just once for your MySQL server, not per database.</p>
</div>
<div class="section" id="s-creating-your-database">
<span id="creating-your-database"></span><h3>Creating your database<a class="headerlink" href="#creating-your-database" title="Permalink to this headline">¶</a></h3>
<p>You can <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/create-database.html">create your database</a> using the command-line tools and this SQL:</p>
<div class="highlight-python"><div class="highlight"><pre>CREATE DATABASE &lt;dbname&gt; CHARACTER SET utf8;
</pre></div>
</div>
<p>This ensures all tables and columns will use UTF-8 by default.</p>
<div class="section" id="s-collation-settings">
<span id="s-mysql-collation"></span><span id="collation-settings"></span><span id="mysql-collation"></span><h4>Collation settings<a class="headerlink" href="#collation-settings" title="Permalink to this headline">¶</a></h4>
<p>The collation setting for a column controls the order in which data is sorted
as well as what strings compare as equal. It can be set on a database-wide
level and also per-table and per-column. This is <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/charset.html">documented thoroughly</a> in
the MySQL documentation. In all cases, you set the collation by directly
manipulating the database tables; Django doesn&#8217;t provide a way to set this on
the model definition.</p>
<p>By default, with a UTF-8 database, MySQL will use the
<tt class="docutils literal"><span class="pre">utf8_general_ci</span></tt> collation. This results in all string equality
comparisons being done in a <em>case-insensitive</em> manner. That is, <tt class="docutils literal"><span class="pre">&quot;Fred&quot;</span></tt> and
<tt class="docutils literal"><span class="pre">&quot;freD&quot;</span></tt> are considered equal at the database level. If you have a unique
constraint on a field, it would be illegal to try to insert both <tt class="docutils literal"><span class="pre">&quot;aa&quot;</span></tt> and
<tt class="docutils literal"><span class="pre">&quot;AA&quot;</span></tt> into the same column, since they compare as equal (and, hence,
non-unique) with the default collation.</p>
<p>In many cases, this default will not be a problem. However, if you really want
case-sensitive comparisons on a particular column or table, you would change
the column or table to use the <tt class="docutils literal"><span class="pre">utf8_bin</span></tt> collation. The main thing to be
aware of in this case is that if you are using MySQLdb 1.2.2, the database
backend in Django will then return bytestrings (instead of unicode strings) for
any character fields it receive from the database. This is a strong variation
from Django&#8217;s normal practice of <em>always</em> returning unicode strings. It is up
to you, the developer, to handle the fact that you will receive bytestrings if
you configure your table(s) to use <tt class="docutils literal"><span class="pre">utf8_bin</span></tt> collation. Django itself should
mostly work smoothly with such columns (except for the <tt class="docutils literal"><span class="pre">contrib.sessions</span></tt>
<tt class="docutils literal"><span class="pre">Session</span></tt> and <tt class="docutils literal"><span class="pre">contrib.admin</span></tt> <tt class="docutils literal"><span class="pre">LogEntry</span></tt> tables described below), but
your code must be prepared to call <tt class="docutils literal"><span class="pre">django.utils.encoding.smart_text()</span></tt> at
times if it really wants to work with consistent data &#8211; Django will not do
this for you (the database backend layer and the model population layer are
separated internally so the database layer doesn&#8217;t know it needs to make this
conversion in this one particular case).</p>
<p>If you&#8217;re using MySQLdb 1.2.1p2, Django&#8217;s standard
<a class="reference internal" href="models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a> class will return unicode strings even
with <tt class="docutils literal"><span class="pre">utf8_bin</span></tt> collation. However, <a class="reference internal" href="models/fields.html#django.db.models.TextField" title="django.db.models.TextField"><tt class="xref py py-class docutils literal"><span class="pre">TextField</span></tt></a>
fields will be returned as an <tt class="docutils literal"><span class="pre">array.array</span></tt> instance (from Python&#8217;s standard
<tt class="docutils literal"><span class="pre">array</span></tt> module). There isn&#8217;t a lot Django can do about that, since, again,
the information needed to make the necessary conversions isn&#8217;t available when
the data is read in from the database. This problem was <a class="reference external" href="http://sourceforge.net/tracker/index.php?func=detail&amp;aid=1495765&amp;group_id=22307&amp;atid=374932">fixed in MySQLdb
1.2.2</a>, so if you want to use <a class="reference internal" href="models/fields.html#django.db.models.TextField" title="django.db.models.TextField"><tt class="xref py py-class docutils literal"><span class="pre">TextField</span></tt></a> with
<tt class="docutils literal"><span class="pre">utf8_bin</span></tt> collation, upgrading to version 1.2.2 and then dealing with the
bytestrings (which shouldn&#8217;t be too difficult) as described above is the
recommended solution.</p>
<p>Should you decide to use <tt class="docutils literal"><span class="pre">utf8_bin</span></tt> collation for some of your tables with
MySQLdb 1.2.1p2 or 1.2.2, you should still use <tt class="docutils literal"><span class="pre">utf8_general_ci</span></tt>
(the default) collation for the <tt class="docutils literal"><span class="pre">django.contrib.sessions.models.Session</span></tt>
table (usually called <tt class="docutils literal"><span class="pre">django_session</span></tt>) and the
<tt class="docutils literal"><span class="pre">django.contrib.admin.models.LogEntry</span></tt> table (usually called
<tt class="docutils literal"><span class="pre">django_admin_log</span></tt>). Those are the two standard tables that use
<a class="reference internal" href="models/fields.html#django.db.models.TextField" title="django.db.models.TextField"><tt class="xref py py-class docutils literal"><span class="pre">TextField</span></tt></a> internally.</p>
<p>Please note that according to <a class="reference external" href="http://dev.mysql.com/doc/refman/5.7/en/charset-unicode-sets.html">MySQL Unicode Character Sets</a>, comparisons for
the <tt class="docutils literal"><span class="pre">utf8_general_ci</span></tt> collation are faster, but slightly less correct, than
comparisons for <tt class="docutils literal"><span class="pre">utf8_unicode_ci</span></tt>. If this is acceptable for your application,
you should use <tt class="docutils literal"><span class="pre">utf8_general_ci</span></tt> because it is faster. If this is not acceptable
(for example, if you require German dictionary order), use <tt class="docutils literal"><span class="pre">utf8_unicode_ci</span></tt>
because it is more accurate.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Model formsets validate unique fields in a case-sensitive manner. Thus when
using a case-insensitive collation, a formset with unique field values that
differ only by case will pass validation, but upon calling <tt class="docutils literal"><span class="pre">save()</span></tt>, an
<tt class="docutils literal"><span class="pre">IntegrityError</span></tt> will be raised.</p>
</div>
</div>
</div>
<div class="section" id="s-connecting-to-the-database">
<span id="connecting-to-the-database"></span><h3>Connecting to the database<a class="headerlink" href="#connecting-to-the-database" title="Permalink to this headline">¶</a></h3>
<p>Refer to the <a class="reference internal" href="settings.html"><em>settings documentation</em></a>.</p>
<p>Connection settings are used in this order:</p>
<ol class="arabic simple">
<li><a class="reference internal" href="settings.html#std:setting-OPTIONS"><tt class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></tt></a>.</li>
<li><a class="reference internal" href="settings.html#std:setting-NAME"><tt class="xref std std-setting docutils literal"><span class="pre">NAME</span></tt></a>, <a class="reference internal" href="settings.html#std:setting-USER"><tt class="xref std std-setting docutils literal"><span class="pre">USER</span></tt></a>, <a class="reference internal" href="settings.html#std:setting-PASSWORD"><tt class="xref std std-setting docutils literal"><span class="pre">PASSWORD</span></tt></a>,
<a class="reference internal" href="settings.html#std:setting-HOST"><tt class="xref std std-setting docutils literal"><span class="pre">HOST</span></tt></a>, <a class="reference internal" href="settings.html#std:setting-PORT"><tt class="xref std std-setting docutils literal"><span class="pre">PORT</span></tt></a></li>
<li>MySQL option files.</li>
</ol>
<p>In other words, if you set the name of the database in <a class="reference internal" href="settings.html#std:setting-OPTIONS"><tt class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></tt></a>,
this will take precedence over <a class="reference internal" href="settings.html#std:setting-NAME"><tt class="xref std std-setting docutils literal"><span class="pre">NAME</span></tt></a>, which would override
anything in a <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/option-files.html">MySQL option file</a>.</p>
<p>Here&#8217;s a sample configuration which uses a MySQL option file:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># settings.py</span>
<span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s">&#39;django.db.backends.mysql&#39;</span><span class="p">,</span>
        <span class="s">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;read_default_file&#39;</span><span class="p">:</span> <span class="s">&#39;/path/to/my.cnf&#39;</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">}</span>
<span class="p">}</span>


<span class="c"># my.cnf</span>
<span class="p">[</span><span class="n">client</span><span class="p">]</span>
<span class="n">database</span> <span class="o">=</span> <span class="n">NAME</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">USER</span>
<span class="n">password</span> <span class="o">=</span> <span class="n">PASSWORD</span>
<span class="n">default</span><span class="o">-</span><span class="n">character</span><span class="o">-</span><span class="nb">set</span> <span class="o">=</span> <span class="n">utf8</span>
</pre></div>
</div>
<p>Several other MySQLdb connection options may be useful, such as <tt class="docutils literal"><span class="pre">ssl</span></tt>,
<tt class="docutils literal"><span class="pre">init_command</span></tt>, and <tt class="docutils literal"><span class="pre">sql_mode</span></tt>. Consult the <a class="reference external" href="http://mysql-python.sourceforge.net/">MySQLdb documentation</a> for
more details.</p>
</div>
<div class="section" id="s-creating-your-tables">
<span id="creating-your-tables"></span><h3>Creating your tables<a class="headerlink" href="#creating-your-tables" title="Permalink to this headline">¶</a></h3>
<p>When Django generates the schema, it doesn&#8217;t specify a storage engine, so
tables will be created with whatever default storage engine your database
server is configured for. The easiest solution is to set your database server&#8217;s
default storage engine to the desired engine.</p>
<p>If you&#8217;re using a hosting service and can&#8217;t change your server&#8217;s default
storage engine, you have a couple of options.</p>
<ul>
<li><p class="first">After the tables are created, execute an <tt class="docutils literal"><span class="pre">ALTER</span> <span class="pre">TABLE</span></tt> statement to
convert a table to a new storage engine (such as InnoDB):</p>
<div class="highlight-python"><div class="highlight"><pre>ALTER TABLE &lt;tablename&gt; ENGINE=INNODB;
</pre></div>
</div>
<p>This can be tedious if you have a lot of tables.</p>
</li>
<li><p class="first">Another option is to use the <tt class="docutils literal"><span class="pre">init_command</span></tt> option for MySQLdb prior to
creating your tables:</p>
<div class="highlight-python"><div class="highlight"><pre>&#39;OPTIONS&#39;: {
   &#39;init_command&#39;: &#39;SET storage_engine=INNODB&#39;,
}
</pre></div>
</div>
<p>This sets the default storage engine upon connecting to the database.
After your tables have been created, you should remove this option as it
adds a query that is only needed during table creation to each database
connection.</p>
</li>
</ul>
</div>
<div class="section" id="s-table-names">
<span id="table-names"></span><h3>Table names<a class="headerlink" href="#table-names" title="Permalink to this headline">¶</a></h3>
<p>There are <a class="reference external" href="http://bugs.mysql.com/bug.php?id=48875">known issues</a> in even the latest versions of MySQL that can cause the
case of a table name to be altered when certain SQL statements are executed
under certain conditions. It is recommended that you use lowercase table
names, if possible, to avoid any problems that might arise from this behavior.
Django uses lowercase table names when it auto-generates table names from
models, so this is mainly a consideration if you are overriding the table name
via the <a class="reference internal" href="models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><tt class="xref py py-class docutils literal"><span class="pre">db_table</span></tt></a> parameter.</p>
</div>
<div class="section" id="s-savepoints">
<span id="savepoints"></span><h3>Savepoints<a class="headerlink" href="#savepoints" title="Permalink to this headline">¶</a></h3>
<p>Both the Django ORM and MySQL (when using the InnoDB <a class="reference internal" href="#mysql-storage-engines"><em>storage engine</em></a>) support database <a class="reference internal" href="../topics/db/transactions.html#topics-db-transactions-savepoints"><em>savepoints</em></a>.</p>
<p>If you use the MyISAM storage engine please be aware of the fact that you will
receive database-generated errors if you try to use the <a class="reference internal" href="../topics/db/transactions.html#topics-db-transactions-savepoints"><em>savepoint-related
methods of the transactions API</em></a>. The reason
for this is that detecting the storage engine of a MySQL database/table is an
expensive operation so it was decided it isn&#8217;t worth to dynamically convert
these methods in no-op&#8217;s based in the results of such detection.</p>
</div>
<div class="section" id="s-notes-on-specific-fields">
<span id="notes-on-specific-fields"></span><h3>Notes on specific fields<a class="headerlink" href="#notes-on-specific-fields" title="Permalink to this headline">¶</a></h3>
<div class="section" id="s-character-fields">
<span id="character-fields"></span><h4>Character fields<a class="headerlink" href="#character-fields" title="Permalink to this headline">¶</a></h4>
<p>Any fields that are stored with <tt class="docutils literal"><span class="pre">VARCHAR</span></tt> column types have their
<tt class="docutils literal"><span class="pre">max_length</span></tt> restricted to 255 characters if you are using <tt class="docutils literal"><span class="pre">unique=True</span></tt>
for the field. This affects <a class="reference internal" href="models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a>,
<a class="reference internal" href="models/fields.html#django.db.models.SlugField" title="django.db.models.SlugField"><tt class="xref py py-class docutils literal"><span class="pre">SlugField</span></tt></a> and
<a class="reference internal" href="models/fields.html#django.db.models.CommaSeparatedIntegerField" title="django.db.models.CommaSeparatedIntegerField"><tt class="xref py py-class docutils literal"><span class="pre">CommaSeparatedIntegerField</span></tt></a>.</p>
</div>
<div class="section" id="s-datetime-fields">
<span id="datetime-fields"></span><h4>DateTime fields<a class="headerlink" href="#datetime-fields" title="Permalink to this headline">¶</a></h4>
<p>MySQL does not store fractions of seconds. Fractions of seconds are truncated
to zero when the time is stored.</p>
</div>
<div class="section" id="s-timestamp-columns">
<span id="timestamp-columns"></span><h4><tt class="docutils literal"><span class="pre">TIMESTAMP</span></tt> columns<a class="headerlink" href="#timestamp-columns" title="Permalink to this headline">¶</a></h4>
<p>If you are using a legacy database that contains <tt class="docutils literal"><span class="pre">TIMESTAMP</span></tt> columns, you must
set <a class="reference internal" href="settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">False</span></tt></a> to avoid data corruption.
<a class="reference internal" href="django-admin.html#django-admin-inspectdb"><tt class="xref std std-djadmin docutils literal"><span class="pre">inspectdb</span></tt></a> maps these columns to
<a class="reference internal" href="models/fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><tt class="xref py py-class docutils literal"><span class="pre">DateTimeField</span></tt></a> and if you enable timezone support,
both MySQL and Django will attempt to convert the values from UTC to local time.</p>
</div>
</div>
<div class="section" id="s-row-locking-with-queryset-select-for-update">
<span id="row-locking-with-queryset-select-for-update"></span><h3>Row locking with <tt class="docutils literal"><span class="pre">QuerySet.select_for_update()</span></tt><a class="headerlink" href="#row-locking-with-queryset-select-for-update" title="Permalink to this headline">¶</a></h3>
<p>MySQL does not support the <tt class="docutils literal"><span class="pre">NOWAIT</span></tt> option to the <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></tt>
statement. If <tt class="docutils literal"><span class="pre">select_for_update()</span></tt> is used with <tt class="docutils literal"><span class="pre">nowait=True</span></tt> then a
<tt class="docutils literal"><span class="pre">DatabaseError</span></tt> will be raised.</p>
</div>
<div class="section" id="s-automatic-typecasting-can-cause-unexpected-results">
<span id="automatic-typecasting-can-cause-unexpected-results"></span><h3>Automatic typecasting can cause unexpected results<a class="headerlink" href="#automatic-typecasting-can-cause-unexpected-results" title="Permalink to this headline">¶</a></h3>
<p>When performing a query on a string type, but with an integer value, MySQL will
coerce the types of all values in the table to an integer before performing the
comparison. If your table contains the values <tt class="docutils literal"><span class="pre">'abc'</span></tt>, <tt class="docutils literal"><span class="pre">'def'</span></tt> and you
query for <tt class="docutils literal"><span class="pre">WHERE</span> <span class="pre">mycolumn=0</span></tt>, both rows will match. Similarly, <tt class="docutils literal"><span class="pre">WHERE</span> <span class="pre">mycolumn=1</span></tt>
will match the value <tt class="docutils literal"><span class="pre">'abc1'</span></tt>. Therefore, string type fields included in Django
will always cast the value to a string before using it in a query.</p>
<p>If you implement custom model fields that inherit from <a class="reference internal" href="models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a>
directly, are overriding <a class="reference internal" href="models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a>, or use
<a class="reference internal" href="models/querysets.html#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><tt class="xref py py-meth docutils literal"><span class="pre">extra()</span></tt></a> or
<a class="reference internal" href="../topics/db/sql.html#django.db.models.Manager.raw" title="django.db.models.Manager.raw"><tt class="xref py py-meth docutils literal"><span class="pre">raw()</span></tt></a>, you should ensure that you
perform the appropriate typecasting.</p>
</div>
</div>
<div class="section" id="s-sqlite-notes">
<span id="s-id11"></span><span id="sqlite-notes"></span><span id="id11"></span><h2>SQLite notes<a class="headerlink" href="#sqlite-notes" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="http://www.sqlite.org/">SQLite</a> provides an excellent development alternative for applications that
are predominantly read-only or require a smaller installation footprint. As
with all database servers, though, there are some differences that are
specific to SQLite that you should be aware of.</p>
<div class="section" id="s-substring-matching-and-case-sensitivity">
<span id="s-sqlite-string-matching"></span><span id="substring-matching-and-case-sensitivity"></span><span id="sqlite-string-matching"></span><h3>Substring matching and case sensitivity<a class="headerlink" href="#substring-matching-and-case-sensitivity" title="Permalink to this headline">¶</a></h3>
<p>For all SQLite versions, there is some slightly counter-intuitive behavior when
attempting to match some types of strings.  These are triggered when using the
<a class="reference internal" href="models/querysets.html#std:fieldlookup-iexact"><tt class="xref std std-lookup docutils literal"><span class="pre">iexact</span></tt></a> or <a class="reference internal" href="models/querysets.html#std:fieldlookup-contains"><tt class="xref std std-lookup docutils literal"><span class="pre">contains</span></tt></a> filters in Querysets. The behavior
splits into two cases:</p>
<p>1. For substring matching, all matches are done case-insensitively. That is a
filter such as <tt class="docutils literal"><span class="pre">filter(name__contains=&quot;aa&quot;)</span></tt> will match a name of <tt class="docutils literal"><span class="pre">&quot;Aabb&quot;</span></tt>.</p>
<p>2. For strings containing characters outside the ASCII range, all exact string
matches are performed case-sensitively, even when the case-insensitive options
are passed into the query. So the <a class="reference internal" href="models/querysets.html#std:fieldlookup-iexact"><tt class="xref std std-lookup docutils literal"><span class="pre">iexact</span></tt></a> filter will behave exactly
the same as the <a class="reference internal" href="models/querysets.html#std:fieldlookup-exact"><tt class="xref std std-lookup docutils literal"><span class="pre">exact</span></tt></a> filter in these cases.</p>
<p>Some possible workarounds for this are <a class="reference external" href="http://www.sqlite.org/faq.html#q18">documented at sqlite.org</a>, but they
aren&#8217;t utilized by the default SQLite backend in Django, as incorporating them
would be fairly difficult to do robustly. Thus, Django exposes the default
SQLite behavior and you should be aware of this when doing case-insensitive or
substring filtering.</p>
</div>
<div class="section" id="s-using-newer-versions-of-the-sqlite-db-api-2-0-driver">
<span id="s-using-newer-versions-of-pysqlite"></span><span id="using-newer-versions-of-the-sqlite-db-api-2-0-driver"></span><span id="using-newer-versions-of-pysqlite"></span><h3>Using newer versions of the SQLite DB-API 2.0 driver<a class="headerlink" href="#using-newer-versions-of-the-sqlite-db-api-2-0-driver" title="Permalink to this headline">¶</a></h3>
<p>Django will use a <tt class="docutils literal"><span class="pre">pysqlite2</span></tt> module in preference to <tt class="docutils literal"><span class="pre">sqlite3</span></tt> as shipped
with the Python standard library if it finds one is available.</p>
<p>This provides the ability to upgrade both the DB-API 2.0 interface or SQLite 3
itself to versions newer than the ones included with your particular Python
binary distribution, if needed.</p>
</div>
<div class="section" id="s-database-is-locked-errors">
<span id="database-is-locked-errors"></span><h3>&#8220;Database is locked&#8221; errors<a class="headerlink" href="#database-is-locked-errors" title="Permalink to this headline">¶</a></h3>
<p>SQLite is meant to be a lightweight database, and thus can&#8217;t support a high
level of concurrency. <tt class="docutils literal"><span class="pre">OperationalError:</span> <span class="pre">database</span> <span class="pre">is</span> <span class="pre">locked</span></tt> errors indicate
that your application is experiencing more concurrency than <tt class="docutils literal"><span class="pre">sqlite</span></tt> can
handle in default configuration. This error means that one thread or process has
an exclusive lock on the database connection and another thread timed out
waiting for the lock the be released.</p>
<p>Python&#8217;s SQLite wrapper has
a default timeout value that determines how long the second thread is allowed to
wait on the lock before it times out and raises the <tt class="docutils literal"><span class="pre">OperationalError:</span> <span class="pre">database</span>
<span class="pre">is</span> <span class="pre">locked</span></tt> error.</p>
<p>If you&#8217;re getting this error, you can solve it by:</p>
<ul>
<li><p class="first">Switching to another database backend. At a certain point SQLite becomes
too &#8220;lite&#8221; for real-world applications, and these sorts of concurrency
errors indicate you&#8217;ve reached that point.</p>
</li>
<li><p class="first">Rewriting your code to reduce concurrency and ensure that database
transactions are short-lived.</p>
</li>
<li><p class="first">Increase the default timeout value by setting the <tt class="docutils literal"><span class="pre">timeout</span></tt> database
option:</p>
<div class="highlight-python"><div class="highlight"><pre>&#39;OPTIONS&#39;: {
    # ...
    &#39;timeout&#39;: 20,
    # ...
}
</pre></div>
</div>
<p>This will simply make SQLite wait a bit longer before throwing &#8220;database
is locked&#8221; errors; it won&#8217;t really do anything to solve them.</p>
</li>
</ul>
</div>
<div class="section" id="s-queryset-select-for-update-not-supported">
<span id="queryset-select-for-update-not-supported"></span><h3><tt class="docutils literal"><span class="pre">QuerySet.select_for_update()</span></tt> not supported<a class="headerlink" href="#queryset-select-for-update-not-supported" title="Permalink to this headline">¶</a></h3>
<p>SQLite does not support the <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></tt> syntax. Calling it will
have no effect.</p>
</div>
<div class="section" id="s-pyformat-parameter-style-in-raw-queries-not-supported">
<span id="pyformat-parameter-style-in-raw-queries-not-supported"></span><h3>&#8220;pyformat&#8221; parameter style in raw queries not supported<a class="headerlink" href="#pyformat-parameter-style-in-raw-queries-not-supported" title="Permalink to this headline">¶</a></h3>
<p>For most backends, raw queries (<tt class="docutils literal"><span class="pre">Manager.raw()</span></tt> or <tt class="docutils literal"><span class="pre">cursor.execute()</span></tt>)
can use the &#8220;pyformat&#8221; parameter style, where placeholders in the query
are given as <tt class="docutils literal"><span class="pre">'%(name)s'</span></tt> and the parameters are passed as a dictionary
rather than a list. SQLite does not support this.</p>
</div>
<div class="section" id="s-parameters-not-quoted-in-connection-queries">
<span id="s-sqlite-connection-queries"></span><span id="parameters-not-quoted-in-connection-queries"></span><span id="sqlite-connection-queries"></span><h3>Parameters not quoted in <tt class="docutils literal"><span class="pre">connection.queries</span></tt><a class="headerlink" href="#parameters-not-quoted-in-connection-queries" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">sqlite3</span></tt> does not provide a way to retrieve the SQL after quoting and
substituting the parameters. Instead, the SQL in <tt class="docutils literal"><span class="pre">connection.queries</span></tt> is
rebuilt with a simple string interpolation. It may be incorrect. Make sure
you add quotes where necessary before copying a query into an SQLite shell.</p>
</div>
</div>
<div class="section" id="s-oracle-notes">
<span id="s-id12"></span><span id="oracle-notes"></span><span id="id12"></span><h2>Oracle notes<a class="headerlink" href="#oracle-notes" title="Permalink to this headline">¶</a></h2>
<p>Django supports <a class="reference external" href="http://www.oracle.com/">Oracle Database Server</a> versions 9i and
higher. Oracle version 10g or later is required to use Django&#8217;s
<tt class="docutils literal"><span class="pre">regex</span></tt> and <tt class="docutils literal"><span class="pre">iregex</span></tt> query operators. You will also need at least
version 4.3.1 of the <a class="reference external" href="http://cx-oracle.sourceforge.net/">cx_Oracle</a> Python driver.</p>
<p>Note that due to a Unicode-corruption bug in <tt class="docutils literal"><span class="pre">cx_Oracle</span></tt> 5.0, that
version of the driver should <strong>not</strong> be used with Django;
<tt class="docutils literal"><span class="pre">cx_Oracle</span></tt> 5.0.1 resolved this issue, so if you&#8217;d like to use a
more recent <tt class="docutils literal"><span class="pre">cx_Oracle</span></tt>, use version 5.0.1.</p>
<p><tt class="docutils literal"><span class="pre">cx_Oracle</span></tt> 5.0.1 or greater can optionally be compiled with the
<tt class="docutils literal"><span class="pre">WITH_UNICODE</span></tt> environment variable.  This is recommended but not
required.</p>
<p>In order for the <tt class="docutils literal"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">migrate</span></tt> command to work, your Oracle
database user must have privileges to run the following commands:</p>
<ul class="simple">
<li>CREATE TABLE</li>
<li>CREATE SEQUENCE</li>
<li>CREATE PROCEDURE</li>
<li>CREATE TRIGGER</li>
</ul>
<p>To run Django&#8217;s test suite, the user needs these <em>additional</em> privileges:</p>
<ul class="simple">
<li>CREATE USER</li>
<li>DROP USER</li>
<li>CREATE TABLESPACE</li>
<li>DROP TABLESPACE</li>
<li>CONNECT WITH ADMIN OPTION</li>
<li>RESOURCE WITH ADMIN OPTION</li>
</ul>
<p>The Oracle database backend uses the <tt class="docutils literal"><span class="pre">SYS.DBMS_LOB</span></tt> package, so your user
will require execute permissions on it. It&#8217;s normally accessible to all users
by default, but in case it is not, you&#8217;ll need to grant permissions like so:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">GRANT</span> <span class="k">EXECUTE</span> <span class="k">ON</span> <span class="n">SYS</span><span class="p">.</span><span class="n">DBMS_LOB</span> <span class="k">TO</span> <span class="k">user</span><span class="p">;</span>
</pre></div>
</div>
<div class="section" id="s-id13">
<span id="id13"></span><h3>Connecting to the database<a class="headerlink" href="#id13" title="Permalink to this headline">¶</a></h3>
<p>To connect using the service name of your Oracle database, your <tt class="docutils literal"><span class="pre">settings.py</span></tt>
file should look something like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s">&#39;django.db.backends.oracle&#39;</span><span class="p">,</span>
        <span class="s">&#39;NAME&#39;</span><span class="p">:</span> <span class="s">&#39;xe&#39;</span><span class="p">,</span>
        <span class="s">&#39;USER&#39;</span><span class="p">:</span> <span class="s">&#39;a_user&#39;</span><span class="p">,</span>
        <span class="s">&#39;PASSWORD&#39;</span><span class="p">:</span> <span class="s">&#39;a_password&#39;</span><span class="p">,</span>
        <span class="s">&#39;HOST&#39;</span><span class="p">:</span> <span class="s">&#39;&#39;</span><span class="p">,</span>
        <span class="s">&#39;PORT&#39;</span><span class="p">:</span> <span class="s">&#39;&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In this case, you should leave both <a class="reference internal" href="settings.html#std:setting-HOST"><tt class="xref std std-setting docutils literal"><span class="pre">HOST</span></tt></a> and <a class="reference internal" href="settings.html#std:setting-PORT"><tt class="xref std std-setting docutils literal"><span class="pre">PORT</span></tt></a> empty.
However, if you don&#8217;t use a <tt class="docutils literal"><span class="pre">tnsnames.ora</span></tt> file or a similar naming method
and want to connect using the SID (&#8220;xe&#8221; in this example), then fill in both
<a class="reference internal" href="settings.html#std:setting-HOST"><tt class="xref std std-setting docutils literal"><span class="pre">HOST</span></tt></a> and <a class="reference internal" href="settings.html#std:setting-PORT"><tt class="xref std std-setting docutils literal"><span class="pre">PORT</span></tt></a> like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s">&#39;django.db.backends.oracle&#39;</span><span class="p">,</span>
        <span class="s">&#39;NAME&#39;</span><span class="p">:</span> <span class="s">&#39;xe&#39;</span><span class="p">,</span>
        <span class="s">&#39;USER&#39;</span><span class="p">:</span> <span class="s">&#39;a_user&#39;</span><span class="p">,</span>
        <span class="s">&#39;PASSWORD&#39;</span><span class="p">:</span> <span class="s">&#39;a_password&#39;</span><span class="p">,</span>
        <span class="s">&#39;HOST&#39;</span><span class="p">:</span> <span class="s">&#39;dbprod01ned.mycompany.com&#39;</span><span class="p">,</span>
        <span class="s">&#39;PORT&#39;</span><span class="p">:</span> <span class="s">&#39;1540&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>You should either supply both <a class="reference internal" href="settings.html#std:setting-HOST"><tt class="xref std std-setting docutils literal"><span class="pre">HOST</span></tt></a> and <a class="reference internal" href="settings.html#std:setting-PORT"><tt class="xref std std-setting docutils literal"><span class="pre">PORT</span></tt></a>, or leave
both as empty strings. Django will use a different connect descriptor depending
on that choice.</p>
</div>
<div class="section" id="s-threaded-option">
<span id="threaded-option"></span><h3>Threaded option<a class="headerlink" href="#threaded-option" title="Permalink to this headline">¶</a></h3>
<p>If you plan to run Django in a multithreaded environment (e.g. Apache using the
default MPM module on any modern operating system), then you <strong>must</strong> set
the <tt class="docutils literal"><span class="pre">threaded</span></tt> option of your Oracle database configuration to True:</p>
<div class="highlight-python"><div class="highlight"><pre>&#39;OPTIONS&#39;: {
    &#39;threaded&#39;: True,
},
</pre></div>
</div>
<p>Failure to do this may result in crashes and other odd behavior.</p>
</div>
<div class="section" id="s-insert-returning-into">
<span id="insert-returning-into"></span><h3>INSERT ... RETURNING INTO<a class="headerlink" href="#insert-returning-into" title="Permalink to this headline">¶</a></h3>
<p>By default, the Oracle backend uses a <tt class="docutils literal"><span class="pre">RETURNING</span> <span class="pre">INTO</span></tt> clause to efficiently
retrieve the value of an <tt class="docutils literal"><span class="pre">AutoField</span></tt> when inserting new rows.  This behavior
may result in a <tt class="docutils literal"><span class="pre">DatabaseError</span></tt> in certain unusual setups, such as when
inserting into a remote table, or into a view with an <tt class="docutils literal"><span class="pre">INSTEAD</span> <span class="pre">OF</span></tt> trigger.
The <tt class="docutils literal"><span class="pre">RETURNING</span> <span class="pre">INTO</span></tt> clause can be disabled by setting the
<tt class="docutils literal"><span class="pre">use_returning_into</span></tt> option of the database configuration to False:</p>
<div class="highlight-python"><div class="highlight"><pre>&#39;OPTIONS&#39;: {
    &#39;use_returning_into&#39;: False,
},
</pre></div>
</div>
<p>In this case, the Oracle backend will use a separate <tt class="docutils literal"><span class="pre">SELECT</span></tt> query to
retrieve AutoField values.</p>
</div>
<div class="section" id="s-naming-issues">
<span id="naming-issues"></span><h3>Naming issues<a class="headerlink" href="#naming-issues" title="Permalink to this headline">¶</a></h3>
<p>Oracle imposes a name length limit of 30 characters. To accommodate this, the
backend truncates database identifiers to fit, replacing the final four
characters of the truncated name with a repeatable MD5 hash value.
Additionally, the backend turns database identifiers to all-uppercase.</p>
<p>To prevent these transformations (this is usually required only when dealing
with legacy databases or accessing tables which belong to other users), use
a quoted name as the value for <tt class="docutils literal"><span class="pre">db_table</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">LegacyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s">&#39;&quot;name_left_in_lowercase&quot;&#39;</span>

<span class="k">class</span> <span class="nc">ForeignModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s">&#39;&quot;OTHER_USER&quot;.&quot;NAME_ONLY_SEEMS_OVER_30&quot;&#39;</span>
</pre></div>
</div>
<p>Quoted names can also be used with Django&#8217;s other supported database
backends; except for Oracle, however, the quotes have no effect.</p>
<p>When running <tt class="docutils literal"><span class="pre">migrate</span></tt>, an <tt class="docutils literal"><span class="pre">ORA-06552</span></tt> error may be encountered if
certain Oracle keywords are used as the name of a model field or the
value of a <tt class="docutils literal"><span class="pre">db_column</span></tt> option.  Django quotes all identifiers used
in queries to prevent most such problems, but this error can still
occur when an Oracle datatype is used as a column name.  In
particular, take care to avoid using the names <tt class="docutils literal"><span class="pre">date</span></tt>,
<tt class="docutils literal"><span class="pre">timestamp</span></tt>, <tt class="docutils literal"><span class="pre">number</span></tt> or <tt class="docutils literal"><span class="pre">float</span></tt> as a field name.</p>
</div>
<div class="section" id="s-null-and-empty-strings">
<span id="null-and-empty-strings"></span><h3>NULL and empty strings<a class="headerlink" href="#null-and-empty-strings" title="Permalink to this headline">¶</a></h3>
<p>Django generally prefers to use the empty string (&#8216;&#8217;) rather than
NULL, but Oracle treats both identically. To get around this, the
Oracle backend ignores an explicit <tt class="docutils literal"><span class="pre">null</span></tt> option on fields that
have the empty string as a possible value and generates DDL as if
<tt class="docutils literal"><span class="pre">null=True</span></tt>. When fetching from the database, it is assumed that
a <tt class="docutils literal"><span class="pre">NULL</span></tt> value in one of these fields really means the empty
string, and the data is silently converted to reflect this assumption.</p>
</div>
<div class="section" id="s-textfield-limitations">
<span id="textfield-limitations"></span><h3><tt class="docutils literal"><span class="pre">TextField</span></tt> limitations<a class="headerlink" href="#textfield-limitations" title="Permalink to this headline">¶</a></h3>
<p>The Oracle backend stores <tt class="docutils literal"><span class="pre">TextFields</span></tt> as <tt class="docutils literal"><span class="pre">NCLOB</span></tt> columns. Oracle imposes
some limitations on the usage of such LOB columns in general:</p>
<ul class="simple">
<li>LOB columns may not be used as primary keys.</li>
<li>LOB columns may not be used in indexes.</li>
<li>LOB columns may not be used in a <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span></tt> list. This means that
attempting to use the <tt class="docutils literal"><span class="pre">QuerySet.distinct</span></tt> method on a model that
includes <tt class="docutils literal"><span class="pre">TextField</span></tt> columns will result in an error when run against
Oracle. As a workaround, use the <tt class="docutils literal"><span class="pre">QuerySet.defer</span></tt> method in conjunction
with <tt class="docutils literal"><span class="pre">distinct()</span></tt> to prevent <tt class="docutils literal"><span class="pre">TextField</span></tt> columns from being included in
the <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span></tt> list.</li>
</ul>
</div>
</div>
<div class="section" id="s-using-a-3rd-party-database-backend">
<span id="s-third-party-notes"></span><span id="using-a-3rd-party-database-backend"></span><span id="third-party-notes"></span><h2>Using a 3rd-party database backend<a class="headerlink" href="#using-a-3rd-party-database-backend" title="Permalink to this headline">¶</a></h2>
<p>In addition to the officially supported databases, there are backends provided
by 3rd parties that allow you to use other databases with Django:</p>
<ul class="simple">
<li><a class="reference external" href="https://github.com/sqlanywhere/sqlany-django">SAP SQL Anywhere</a></li>
<li><a class="reference external" href="http://code.google.com/p/ibm-db/">IBM DB2</a></li>
<li><a class="reference external" href="http://django-mssql.readthedocs.org/en/latest/">Microsoft SQL Server</a></li>
<li><a class="reference external" href="https://github.com/maxirobaina/django-firebird">Firebird</a></li>
<li><a class="reference external" href="https://github.com/lionheart/django-pyodbc/">ODBC</a></li>
<li><a class="reference external" href="http://code.google.com/p/adsdb-django/">ADSDB</a></li>
</ul>
<p>The Django versions and ORM features supported by these unofficial backends
vary considerably. Queries regarding the specific capabilities of these
unofficial backends, along with any support queries, should be directed to
the support channels provided by each 3rd party project.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Databases</a><ul>
<li><a class="reference internal" href="#general-notes">General notes</a><ul>
<li><a class="reference internal" href="#persistent-connections">Persistent connections</a><ul>
<li><a class="reference internal" href="#connection-management">Connection management</a></li>
<li><a class="reference internal" href="#caveats">Caveats</a></li>
</ul>
</li>
<li><a class="reference internal" href="#encoding">Encoding</a></li>
</ul>
</li>
<li><a class="reference internal" href="#postgresql-notes">PostgreSQL notes</a><ul>
<li><a class="reference internal" href="#postgresql-connection-settings">PostgreSQL connection settings</a></li>
<li><a class="reference internal" href="#optimizing-postgresql-s-configuration">Optimizing PostgreSQL&#8217;s configuration</a></li>
<li><a class="reference internal" href="#autocommit-mode">Autocommit mode</a></li>
<li><a class="reference internal" href="#isolation-level">Isolation level</a></li>
<li><a class="reference internal" href="#indexes-for-varchar-and-text-columns">Indexes for <tt class="docutils literal"><span class="pre">varchar</span></tt> and <tt class="docutils literal"><span class="pre">text</span></tt> columns</a></li>
</ul>
</li>
<li><a class="reference internal" href="#mysql-notes">MySQL notes</a><ul>
<li><a class="reference internal" href="#version-support">Version support</a></li>
<li><a class="reference internal" href="#storage-engines">Storage engines</a></li>
<li><a class="reference internal" href="#mysql-db-api-drivers">MySQL DB API Drivers</a><ul>
<li><a class="reference internal" href="#id8">MySQLdb</a></li>
<li><a class="reference internal" href="#id9">mysqlclient</a></li>
<li><a class="reference internal" href="#id10">MySQL Connector/Python</a></li>
</ul>
</li>
<li><a class="reference internal" href="#time-zone-definitions">Time zone definitions</a></li>
<li><a class="reference internal" href="#creating-your-database">Creating your database</a><ul>
<li><a class="reference internal" href="#collation-settings">Collation settings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#connecting-to-the-database">Connecting to the database</a></li>
<li><a class="reference internal" href="#creating-your-tables">Creating your tables</a></li>
<li><a class="reference internal" href="#table-names">Table names</a></li>
<li><a class="reference internal" href="#savepoints">Savepoints</a></li>
<li><a class="reference internal" href="#notes-on-specific-fields">Notes on specific fields</a><ul>
<li><a class="reference internal" href="#character-fields">Character fields</a></li>
<li><a class="reference internal" href="#datetime-fields">DateTime fields</a></li>
<li><a class="reference internal" href="#timestamp-columns"><tt class="docutils literal"><span class="pre">TIMESTAMP</span></tt> columns</a></li>
</ul>
</li>
<li><a class="reference internal" href="#row-locking-with-queryset-select-for-update">Row locking with <tt class="docutils literal"><span class="pre">QuerySet.select_for_update()</span></tt></a></li>
<li><a class="reference internal" href="#automatic-typecasting-can-cause-unexpected-results">Automatic typecasting can cause unexpected results</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sqlite-notes">SQLite notes</a><ul>
<li><a class="reference internal" href="#substring-matching-and-case-sensitivity">Substring matching and case sensitivity</a></li>
<li><a class="reference internal" href="#using-newer-versions-of-the-sqlite-db-api-2-0-driver">Using newer versions of the SQLite DB-API 2.0 driver</a></li>
<li><a class="reference internal" href="#database-is-locked-errors">&#8220;Database is locked&#8221; errors</a></li>
<li><a class="reference internal" href="#queryset-select-for-update-not-supported"><tt class="docutils literal"><span class="pre">QuerySet.select_for_update()</span></tt> not supported</a></li>
<li><a class="reference internal" href="#pyformat-parameter-style-in-raw-queries-not-supported">&#8220;pyformat&#8221; parameter style in raw queries not supported</a></li>
<li><a class="reference internal" href="#parameters-not-quoted-in-connection-queries">Parameters not quoted in <tt class="docutils literal"><span class="pre">connection.queries</span></tt></a></li>
</ul>
</li>
<li><a class="reference internal" href="#oracle-notes">Oracle notes</a><ul>
<li><a class="reference internal" href="#id13">Connecting to the database</a></li>
<li><a class="reference internal" href="#threaded-option">Threaded option</a></li>
<li><a class="reference internal" href="#insert-returning-into">INSERT ... RETURNING INTO</a></li>
<li><a class="reference internal" href="#naming-issues">Naming issues</a></li>
<li><a class="reference internal" href="#null-and-empty-strings">NULL and empty strings</a></li>
<li><a class="reference internal" href="#textfield-limitations"><tt class="docutils literal"><span class="pre">TextField</span></tt> limitations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-a-3rd-party-database-backend">Using a 3rd-party database backend</a></li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="contrib/webdesign.html">django.contrib.webdesign</a></li>
    
    
      <li>Next: <a href="django-admin.html">django-admin.py and manage.py</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="index.html">API Reference</a>
        
        <ul><li>Databases</li></ul>
        </li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/ref/databases.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="contrib/webdesign.html" title="django.contrib.webdesign">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="django-admin.html" title="django-admin.py and manage.py">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>